package org.csu.jpetstore.service;

import org.csu.jpetstore.domain.Account;
import org.csu.jpetstore.domain.Cart;
import org.csu.jpetstore.domain.CartItem;
import org.csu.jpetstore.domain.Item;
import org.csu.jpetstore.persistence.CartMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class CartService {
    @Autowired
    private CartMapper cartMapper;
    
    @Autowired
    private CatalogService catalogService;

    // 检查用户购物车是否存在
    public boolean isCartExist(String username) {
        return cartMapper.isExist(username);
    }

    // 添加商品到购物车
    public void addItemToCart(String username, String itemId, int quantity) {
        if (cartMapper.isExist(username)) {
            cartMapper.updateCartItemQuantity(username, itemId, quantity);
        } else {
            cartMapper.insertCartItem(username, itemId, quantity);
        }
    }

    // 从购物车中删除商品
    public void removeItemFromCart(String username, String itemId) {
        cartMapper.deleteCartItem(username, itemId);
    }

    // 获取用户的购物车商品列表
    public List<CartItem> getCartItems(String username) {
        return cartMapper.getCartItemsByUsername(username);
    }

    // 更新购物车商品数量
    public void updateCartItemQuantity(String username, String itemId, int quantity) {
        if (quantity <= 0) {
            cartMapper.deleteCartItem(username, itemId);
        } else {
            cartMapper.updateCartItemQuantity(username, itemId, quantity);
        }
    }

    // 清空用户的购物车
    public void clearCart(String username) {
        cartMapper.deleteAllCartItems(username);
    }

    // 获取用户购物车中的某个商品
    public Item getCartItem(String username) {
        String itemId = cartMapper.getItemIdByUsername(username);
        return itemId != null ? catalogService.getItem(itemId) : null;
    }

    // 获取用户购物车中的所有商品
    public List<String> getCartItemIds(String username) {
        return cartMapper.getItemIdListByUsername(username);
    }

    // 批量添加商品到购物车
    public void batchAddItemsToCart(String username, List<CartItem> items) {
        cartMapper.batchInsertCartItems(username, items);
    }
}
